#include "gelement.h"
#include "delement.h"
#include <QtSvg/QSvgRenderer>
#include <QtGui/QGraphicsTextItem>
#include <QtXml/QDomElement>
#include <QtGui/QInputDialog>
//#include <QtGui/QTextCursor>

QSvgRenderer GElement::token;
//QSvgRenderer GElement::multiToken;

GElement::GElement(DElement* aDElement, QGraphicsItem *parent) 
	: QGraphicsItemGroup(parent) 
{
	if (!token.isValid()) 
		token.load(QString(":/elements/token.svg"));
	//if (!multiToken.isValid()) 
	//	multiToken.load(QString(":/elements/multiToken.svg"));
	
	keyDElement = aDElement;

	mObjectName.setPlainText(keyDElement->displayName() + QVariant(keyDElement->count()).toString());
	mObjectName.setParentItem(this);
	mObjectName.setPos(-mObjectName.boundingRect().bottomLeft());
	mObjectName.setVisible(true);
	//mObjectName.setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsFocusable);
	//mObjectName.setTextInteractionFlags( Qt::TextEditorInteraction );
	//addToGroup(&mObjectName);

	centerSvg.setSharedRenderer(keyDElement->renderer());
	centerSvg.setParentItem(this);
	//centerSvg.setPos(mObjectName.boundingRect().bottomLeft());
	addToGroup(&centerSvg);

	//mIsToken = false;
	mToken.setSharedRenderer(&token);
	mToken.setParentItem(this);
	mToken.setPos(svgCenter()-mToken.boundingRect().center());
	mToken.setVisible(false);
	mToken.setZValue(centerSvg.zValue()+1);

	setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable );
}

QString GElement::elementName()
{
	return mObjectName.toPlainText();
}

void GElement::setElementName(const QString & name)
{
	mObjectName.setPlainText(name);
}

QString GElement::kind()
{
	return keyDElement->kind();
}

QString GElement::className()
{
	return keyDElement->className();
}

QPointF GElement::svgCenter() 
{ 
	//Group is different from Parent.
	return centerSvg.pos()+centerSvg.boundingRect().center(); 
}

void GElement::setTokens(const QList<Token*>& tokenList)
{
	mTokens = tokenList;
	mToken.setVisible( !mTokens.isEmpty() );
}

const QList<Token*>& GElement::tokens() const
{
	return mTokens;
}

void GElement::addToken(Token* newToken)
{
	mTokens.append(newToken);
	mToken.setVisible(true);
}

void GElement::deleteToken(int index)
{
	Token* aToken = mTokens[index];
	mTokens.removeAt(index);
	delete aToken;
	mToken.setVisible(!mTokens.isEmpty());
}